import NProgress from 'nprogress'
import { setPageTitle } from '@/utils'
import router from './index'
import { getToken } from '@/utils/auth'
import 'nprogress/nprogress.css'
import { HomePath } from '@/config'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login']

router.beforeEach(async (to, _, next) => {
  NProgress.start()
  const token = getToken()

  if (token) {
    if (to.path === '/login') {
      next({ path: HomePath })
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach((to) => {
  setPageTitle(to.meta.title)
  NProgress.done()
})
